"""测试URL"""
# -*- coding:utf-8 -*-
from ppts.entity.PagePerformanceData import PagePerformanceData


class TestUrl:

    def __init__(self, config, pass_time=3000, challenge_time=2000):
        # 是否需要收集数据
        self.collect_data = config.get('collect_data', True)
        # 名称，如不自定义就使用页面标题
        self.name = config.get('name', None)
        # 要访问的url
        self.url = config.get('url', None)
        # 当前url的自定义cookie
        self.custom_cookie = config.get('custom_cookie', None)
        # 是否为单页面应用，单页面应用会使用自定义方式获取加载时间
        self.spa = config.get('spa', False)
        # 单页面应用，切换的话URL不变，需要手动设置检查元素
        self.check_element = config.get('check_element', None)
        # 要切换的窗口index, 从1开始，从左到右
        self.tab = config.get('tab', None)
        # 达标值
        self.pass_time = config.get('pass_time', pass_time)
        # 挑战值
        self.challenge_time = config.get('challenge_time', challenge_time)
        # 检查元素by_type ,暂时废弃
        self.check_by_type = config.get('check_by_type', None)
        # 检查元素by_value ,暂时废弃
        self.check_by_value = config.get('check_by_value', None)
        # 是否需要在页面加载完成之后进行截图
        self.screenshot = config.get('screenshot', False)
        # 使用脚本操作：例如要做业务，解析数据，切换iframe等
        self.script = config.get('script', None)
        # frame定位  ,暂时废弃
        self.frame = config.get('frame', None)
        # 最终测试结果数据
        self.pts_data = []
        # 平均值
        self.pts_avg_data = None
        # 最大值
        self.pts_max_data = None
        # 最小值
        self.pts_min_data = None
        # 全部的值
        self.pts_total_data = None

        # 页面请求报错的总数
        self.page_request_failed_count = 0

        # 页面接口报错数-按单接口区分
        self.single_request_details = {
            # 'https://www.baidu.com': {
            #     'errorCount': 0,
            #     'times': [],
            #     'codes': [],
            #     'details': []
            # }
        }

        # 是否达标，小于pass_time
        self.is_pass = False
        # 是否达到挑战值
        self.is_challenge = False
        # 自定义cookie列表
        self.cookie_list = []
        if self.custom_cookie:
            temp_list = self.custom_cookie.split(';')
            for temp in temp_list:
                temp2_list = str(temp).split('=', 1)
                self.cookie_list.append({
                    'name': temp2_list[0].strip(),
                    'value': temp2_list[1].strip()
                })

    def get_cookie_list(self):
        return self.cookie_list
        # from ppts.entity.GlobalTestObject import global_test_object
        # return self.cookie_list if self.cookie_list and len(self.cookie_list) > 0\
        #     else global_test_object.test_config.cookie_list

    # 计算一些平均值,最大值，最小值
    def count_data(self):
        if not self.collect_data or len(self.pts_data) == 0:
            return
        self.pts_avg_data = PagePerformanceData()
        self.pts_max_data = PagePerformanceData()
        self.pts_min_data = PagePerformanceData()
        self.pts_total_data = PagePerformanceData()
        num = 0
        for pd in self.pts_data:
            if pd.success:
                self.parse_data(pd, 'request_time')
                self.parse_data(pd, 'redirect_time')
                self.parse_data(pd, 'domain_lookup_time')
                self.parse_data(pd, 'connect_time')
                self.parse_data(pd, 'dom_render_time')
                self.parse_data(pd, 'blank_screen_time')
                self.parse_data(pd, 'page_load_time')
                self.count_request(pd.request_info)
                num = num + 1
        if num > 0:
            # 计算平均值
            self.pts_avg_data.request_time = int(self.pts_total_data.request_time / num)
            self.pts_avg_data.redirect_time = int(self.pts_total_data.redirect_time / num)
            self.pts_avg_data.domain_lookup_time = int(self.pts_total_data.domain_lookup_time / num)
            self.pts_avg_data.connect_time = int(self.pts_total_data.connect_time / num)
            self.pts_avg_data.dom_render_time = int(self.pts_total_data.dom_render_time / num)
            self.pts_avg_data.blank_screen_time = int(self.pts_total_data.blank_screen_time / num)
            self.pts_avg_data.page_load_time = int(self.pts_total_data.page_load_time / num)
        if self.pts_avg_data.page_load_time <= self.pass_time:
            self.is_pass = True
        if self.pts_avg_data.page_load_time <= self.challenge_time:
            self.is_challenge = True

        # 计算单个请求的平均值
        max_time = 0
        min_time = 0
        if len(self.single_request_details.keys()) > 0:
            for name, data in self.single_request_details.items():
                if len(data['times']) > 0:
                    total_time = sum(data['times'])
                    data['avgTime'] = round(total_time / len(data['times']), 1)
                    data['minTime'] = min(data['times'])
                    data['maxTime'] = max(data['times'])
                    data['totalCount'] = len(data['times'])

    def parse_data(self, current_data, pts_type):
        setattr(self.pts_total_data, pts_type, getattr(self.pts_total_data, pts_type) + getattr(current_data, pts_type))
        max_type_d = getattr(self.pts_max_data, pts_type)
        min_type_d = getattr(self.pts_min_data, pts_type)
        current_type_d = getattr(current_data, pts_type)
        if max_type_d == 0 or max_type_d < current_type_d:
            setattr(self.pts_max_data, pts_type, current_type_d)
        if min_type_d == 0 or min_type_d > current_type_d:
            setattr(self.pts_min_data, pts_type, current_type_d)

    def count_request(self, request_info):
        if request_info and len(request_info) > 0:
            for info in request_info:
                if info.get('entryType') != 'resource':
                    continue
                if str(info.get('renderBlockingStatus')) == 'non-blocking':
                    info['responseStatus'] = 200
                name = info.get("name")
                if name not in self.single_request_details:
                    self.single_request_details[name] = {
                        'errorCount': 0,
                        'avgTime': 0,
                        'maxTime': 0,
                        'minTime': 0,
                        'totalCount': 0,
                        'times': [],
                        'codes': [],
                        'details': []
                    }

                self.single_request_details[name]['times'].append(round(info.get('duration'), 1))
                self.single_request_details[name]['codes'].append(info.get('responseStatus'))
                self.single_request_details[name]['details'].append({
                    'name': name,
                    # 请求耗时
                    'duration': round(info.get('duration'), 1),
                    # 请求类型
                    'initiatorType': info['initiatorType'],
                    # 响应类型
                    'entryType': info['entryType'],
                    # 状态码
                    'responseStatus': info['responseStatus']
                })
                if str(info.get('responseStatus')) != '200' and str(info.get('responseStatus')) != '304':
                    self.page_request_failed_count += 1
                    self.single_request_details[name]['errorCount'] += 1

